package sort;

/**
 * @author LQQ
 * @version V1.0
 * @Package PACKAGE_NAME
 * @date 2020/10/11 22:15
 * @Description
 */
public class QuickSort {
    public static int[] quickSort(int[] array, int start, int end) {
        if (array.length < 1 || start < 0 || end >= array.length || start > end) return null;
        int smallIndex = partition(array, start, end);
        if (smallIndex > start)
            quickSort(array, start, smallIndex - 1);
        if (smallIndex < end)
            quickSort(array, smallIndex + 1, end);
        return array;
    }

    //快速排序算法——partition
    public static int partition(int[] array, int start, int end) {
        int pivot = (int) (start + Math.random() * (end - start + 1));
        int smallIndex = start - 1;
        swap(array, pivot, end);
        for (int i = start; i <= end; i++)
            if (array[i] <= array[end]) {
                smallIndex++;
                if (i > smallIndex)
                    swap(array, i, smallIndex);
            }
        return smallIndex;
    }


    // 交换数组内两个元素
    public static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    public static void main(String[] args) {
        int[] array = new int[]{11, 1, 3, 1, 4, 7, 45, 76, 23, 7, 34, 9, 90, 0};
        array = quickSort(array,0,array.length);
        for (int num : array) {
            System.out.println(num);
        }
    }
}
